package com.yi.mall.pay.controller;

import com.yi.mall.common.model.OrderInfo;
import com.yi.mall.common.utils.ResponseEnum;
import com.yi.mall.common.utils.Result;
import com.yi.mall.pay.config.AlipayConfiguration;
import com.yi.mall.pay.service.IAlipayService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

import static org.apache.rocketmq.common.message.MessageDecoder.CHARSET_UTF8;

/**
 * <p>
 * 支付记录表 前端控制器
 * </p>
 *
 * @author zzy
 * @since 2025-07-30
 */
@RestController
@RequestMapping("/alipay")
public class AlipayController {
    @Autowired
    private IAlipayService alipayService;
    @Autowired
    private AlipayConfiguration alipayConfiguration;
    @GetMapping("/pay")
    public void pay(OrderInfo orderInfo, HttpServletResponse response) throws Exception {
        // 调用业务
        String result = alipayService.pay(orderInfo);
        // 返回结果给前端:将表单直接输出到页面，用户点击后会跳转到支付宝支付页面
        response.setContentType("text/html;charset=" + CHARSET_UTF8);
        response.getWriter().write(result);
        response.getWriter().flush();
        response.getWriter().close();
    }
    @GetMapping("/return")
    public void payReturn(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 设置响应的字符编码为UTF-8，防止中文乱码
        response.setCharacterEncoding("UTF-8");
        // 设置响应的内容类型为HTML，并指定字符编码为UTF-8
        response.setContentType("text/html; charset=UTF-8");
        // 重定向到指定的HTML页面（需要提前与前端沟通好支付成功后要跳转的页面）
        response.sendRedirect(alipayConfiguration.getSuccessUrl());
    }
    @PostMapping("/notify")
    public void payNotify(HttpServletRequest request) {
        // 获取支付宝返回的各个参数
        Map<String, String[]> result = request.getParameterMap();
        // 检查交易状态是否为成功
        if ("TRADE_SUCCESS".equals(request.getParameter("trade_status"))) {
            // 通知处理
            alipayService.payNotify(result);
        }
    }
    @PostMapping("/query")
    public Result query(String outTradeNo) throws Exception {
        String result = alipayService.query(outTradeNo);
        return Result.success(ResponseEnum.SUCCESS,result);
    }
}
